﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OrderAggregator.Formulas;

namespace OrderAggregator.UI
{
    /// <summary>
    /// Formula edit control
    /// </summary>
    public partial class FormulaEditControl : UserControl
    {


        public FormulaEditControl()
        {
            InitializeComponent();

            txtBoxFormula.TextChanged += delegate
                                             {
                                                 mnuCompile.Enabled = !string.IsNullOrEmpty(Formula);
                                                 mnuCalculate.Enabled = mnuCompile.Enabled;
                                             };

            //decimal value = 0;
            //decimal res = 8*Math.Round(1 + value/8);


            AddStandartFormula("Формула \"Минимальная партия\"",
                () =>
@"//8 - мин. партия 
return 8 * Math.Ceiling(value/8);"
                );
//            AddStandartFormula("Формула \"Минимальная партия с округлением\"",
//                () =>
//@"//8 - мин. партия 
//decimal x = Math.Round(value/8);
//if (x < 1) x = 1;
//return 8 * x;"
//);
            
        }


        /// <summary>
        /// Get or set Formula
        /// </summary>
        public string Formula
        {
            get
            {
                return txtBoxFormula.Text;
            }
            set
            {
                txtBoxFormula.Text = value;
            }
        }

        private void mnuCompile_Click(object sender, EventArgs e)
        {
            Compile();
        }

        private void mnuCalculate_Click(object sender, EventArgs e)
        {
            var formulaManager = FormulaManager.Default;

            var formula = this.Formula;

            try
            {
                formulaManager.PreCompile(new[] { formula });

                var formulaDelegate = formulaManager.GetFormulaDelegate(formula);

                var res = formulaDelegate.Invoke(nrcValue.Value);

                lblResult.ForeColor = Color.Black;
                lblResult.Text = res.ToString();
            }
            catch (Exception ex)
            {
                lblResult.ForeColor = Color.Red;
                lblResult.Text = ex.Message;
            }
        }

        private void Compile()
        {
            var formulaManager = FormulaManager.Default;

            string formula = this.Formula;

            try
            {
                formulaManager.PreCompile(new[] { formula });

                lblResult.ForeColor = Color.Black;
                lblResult.Text = "Компиляция прошла успешно";
            }
            catch (Exception ex)
            {
                lblResult.ForeColor = Color.Red;
                lblResult.Text = ex.Message;
            }
        }

        private void AddStandartFormula(string formulaName, Func<string> expressionFact)
        {
            var item = mnuInsert.DropDownItems.Add(formulaName);

            item.Click += delegate
                              {
                                  var expression = expressionFact.Invoke();

                                  if (string.IsNullOrEmpty(expression))
                                  {
                                      return;
                                  }

                                  int selectionStart = txtBoxFormula.SelectionStart;

                                  if (selectionStart >= 0)
                                  {
                                      string formula = Formula;

                                      if (txtBoxFormula.SelectionLength > 0)
                                      {
                                          formula = formula.Remove(selectionStart, txtBoxFormula.SelectionLength);
                                      }

                                      formula = formula.Insert(selectionStart, expression);

                                      Formula = formula;
                                      txtBoxFormula.Select(selectionStart, expression.Length);
                                  }
                                  else
                                  {
                                      Formula = expression;
                                      txtBoxFormula.Select(0, expression.Length);
                                  }

                              };
        }
    }

}
